package org.lgiavedoni.android.franq.command.system;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.lgiavedoni.android.franq.core.bean.ConfigBean;
import org.lgiavedoni.android.franq.core.command.Command;
import org.lgiavedoni.android.franq.core.speak.CommonPhraseHelper;
import org.lgiavedoni.android.franq.service.communication.CommunicationService;
import org.lgiavedoni.android.franq.service.config.ConfigService;
import org.lgiavedoni.android.franq.util.collection.CollectionUtils;

public class ConfigCommand extends Command {

	private static final String OPTION_LIST = "list";
	private static final String OPTION_SET = "set";
	private static final String OPTION_APPLY = "apply";
	private static final String OPTION_RESET = "reset";

	@Override
	public void setOptions(Options options) {
		options.addOption(OPTION_LIST, false, "List current configuration");
		options.addOption(OPTION_SET, false, "Set new config value. Usage: key value");
		options.addOption(OPTION_APPLY, false, "Apply the new config values");
		options.addOption(OPTION_RESET, false, "Reset the completely configuration");
	}

	@Override
	public boolean execute(CommandLine cmd) throws Exception {
		if (cmd.hasOption(OPTION_LIST)) {
			List<ConfigBean> values = new ArrayList<ConfigBean>(ConfigService.inst.getValues());
			Collections.sort(values);
			CommunicationService.inst.sendDefaultTextMessage("Config values: " + CollectionUtils.toString(values, "\n"));
			return true;
		}
		if (cmd.hasOption(OPTION_SET)) {
			String key = cmd.getArgs()[0];
			String value = cmd.getArgs()[1];
			String oldValue = ConfigService.inst.getValue(key);
			ConfigService.inst.setValue(key, value);
			CommunicationService.inst.sendDefaultTextMessage(key + ", old value[" + oldValue + "] new value[" + value + "]");
			return true;
		}
		if (cmd.hasOption(OPTION_APPLY)) {
			ConfigService.inst.updateConfig();
			CommunicationService.inst.sendMessage(CommonPhraseHelper.DONE);
			return true;
		}
		if (cmd.hasOption(OPTION_RESET)) {
			ConfigService.inst.restoreConfig();
			CommunicationService.inst.sendMessage(CommonPhraseHelper.DONE);
			return true;
		}

		return false;
	}

	@Override
	public String getCommandText() {
		return "config";
	}
}